import axios from 'axios';
import website from '@/const/website';
import { serialize } from '@/util';
import { aesDecrypt, aesEncrypt } from '@/util/encryption';
import { getStore } from '@/util/store';
import NProgress from 'nprogress'; // progress bar
import errorCode from '@/const/errorCode';
// eslint-disable-next-line
import router from '@/router/router';
import { Message, MessageBox } from 'element-ui';
import 'nprogress/nprogress.css';
import qs from 'qs';
import store from '@/store'; // progress bar style
axios.defaults.timeout = 300000;
// 返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};
// 跨域请求，允许保存cookie
// axios.defaults.withCredentials = true;
// axios.defaults.baseURL = '/api';
// NProgress Configuration
NProgress.configure({
  showSpinner: false,
});

// HTTPrequest拦截
axios.interceptors.request.use(
  (config) => {
    NProgress.start(); // start progress bar
    const TENANT_ID = getStore({ name: 'tenantId' });
    const isToken = (config.headers || {}).isToken === false;
    const token = store.getters.access_token;
    if (token && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + token; // token
    }

    if (config.url.indexOf('/qiNiuUploadFile') !== -1) {
      config.baseURL = '';
      // 暂时写死
      config.headers['Authorization'] =
        'Bearer ' +
        'Zv4nKKB9z_M3StKd2z_sYhvpMNsAJkd8ws88epHb:_MggBlhiDGym_XSHWjj0mvUNVbc=:eyJzY29wZSI6Im1heWEtcGV0LWRldiIsImRlYWRsaW5lIjoyNjgxOTczMjg2fQ==';
    } else {
      config.baseURL = '/api';
    }
    if (TENANT_ID) {
      config.headers['TENANT-ID'] = TENANT_ID; // 租户ID
    }

    // headers中配置serialize为true开启序列化
    if (config.method === 'post' && config.headers.serialize) {
      config.data = serialize(config.data);
      delete config.data.serialize;
    }

    // 请求报文加密
    if (config.headers['Enc-Flag']) {
      config.data = {
        encryption: aesEncrypt(
          JSON.stringify(config.data),
          website.encPassword
        ),
      };
    }

    if (config.method === 'get') {
      config.paramsSerializer = function (params) {
        return qs.stringify(params, { arrayFormat: 'repeat' });
      };
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// HTTPresponse拦截
axios.interceptors.response.use(
  (res) => {
    NProgress.done();
    const status = Number(res.status) || 200;
    const message = res.data.msg || errorCode[status] || errorCode['default'];

    // 后台定义 424 针对令牌过去的特殊响应码
    if (status === 424) {
      MessageBox.confirm('令牌状态已过期，请点击重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          store.dispatch('LogOut').then(() => {
            // 刷新登录页面，避免多次弹框
            window.location.reload();
          });
        })
        .catch(() => {});
      return;
    }
    if (
      status !== 200 ||
      (res.data.code !== 0 && typeof res.data.code !== 'undefined')
    ) {
      Message({
        message: message,
        type: 'error',
      });
      return Promise.reject(new Error(message));
    }

    // 针对密文返回解密
    if (res.data.encryption) {
      const originData = JSON.parse(
        aesDecrypt(res.data.encryption, website.encPassword)
      );
      res.data = originData;
      return res;
    }

    return res;
  },
  (error) => {
    // 处理 503 网络异常
    if (error.response.status === 503) {
      Message({
        message: error.response.data.msg,
        type: 'error',
      });
    }
    NProgress.done();
    return Promise.reject(new Error(error));
  }
);

export default axios;
